<?php
namespace app\admin\controller;

use think\Controller;
use think\Request;
use think\Loader;
use app\admin\model\AdminUser as UserModel;

class Login extends Controller
{
    protected $user_model;

    public function __construct(Request $request = null)
    {
        parent::__construct($request);

        $this->user_model = new UserModel();
    }

    public function index(Request $request = null)
    {
        if ($request->isPOST()) {
            // var_dump(input('post.'));
            // exit;
            $username = trim(input('post.username'));
            $password = trim(input('post.password'));
            $verify = trim(input('post.verify'));

            if (!$username || !$password || !$verify) {
                $this->error('用户名/密码/验证码不能为空');
            }

            if (!captcha_check($verify)) {
                $this->error('验证码不正确', 'index');
            }

            $info = $this->user_model->getLogInfo($username);

            if (!$info || md5($password) != $info->password) {
                $this->error('用户名/密码不正确', 'index');
            }

            $time = time();

            $ip = inet_aton($request->ip());

            $result = $this->user_model->save(['login_time' => $time, 'login_ip' => $ip], ['id' => $info->id]);

            if ($result === false) {
                $this->error('登陆失败,请稍后重试', 'index');
            }
            
            //记录登陆信息
            $browser = browser_info();

            @$result = model('login_note')->save([
                'userid'=>$info['id'],
                'time'=>$time,
                'ip'=>$ip,
                'browser'=>$browser
            ]);
            
            session('uid', $info->id);
            session('username', $info->username);
            session('last_time', $info->login_time);
            session('last_ip', $info->login_ip);

            $this->success('登入成功', 'index/index');
        } else {
            if (session('?user_name')) {
                $this->success('您已登入', 'index/index');
            } else {
                return $this->fetch();
            }
        }
    }

    /**
     * 登出
     */
    public function logout()
    {
        session(null);
        return $this->fetch('index');
    }
}
